package example.hello_security.config.handler;

import cn.hutool.json.JSONUtil;
import example.hello_security.result.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * description 自定义拒绝访问处理器
 * @author zken
 * CreateDate 2024/10/28 14:10:18
 */
@Component
public class CustomAccessDenyHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        String token = request.getParameter("token");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        Result<String> error = Result.error("权限不足，请重新认证或连接管理员");
        String jsonError = JSONUtil.toJsonStr(error);
        response.getWriter().write(jsonError);
    }
}
